package spectra.ee.web.common.service;

import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;

import spectra.base.log.Logger;
import spectra.base.sql.ibatis.SqlMapperWeb;
import spectra.base.util.DateUtil;
import spectra.ee.web.WebPublic;
import spectra.ee.web.common.model.Favorite;
import spectra.ee.web.common.model.IdListForm;

import com.ibatis.sqlmap.client.SqlMapClient;

/**
 * 즐겨찾기 클래스.
 *
 * @author kmhan
 */
public class FavoriteServiceBase
{

    /** Logger객체. */
    private static Logger logger = Logger.getLoggerInstance(FavoriteServiceBase.class.getName());

    /** SqlMapClient 객체. */
    protected static SqlMapClient sqlMap = SqlMapperWeb.getSqlMapWebInstance();

    /**
     * 상담원아이디로 즐겨찾기 목록을 가져오는 메소드
     * @param accountId
     * @return
     */
    public String selectFavoriteListForTree(String accountId)
    {
        Favorite favorite = null;
        String jsonFavoriteList = "[";

        try
        {
            List favoriteList = (List)sqlMap.queryForList("Favorite.selectListForTreeByAccountId", accountId);
            if (favoriteList != null && favoriteList.size() > 0)
            {
                for (int i = 0; i < favoriteList.size(); i++)
                {
                    favorite = (Favorite) favoriteList.get(i);
                    jsonFavoriteList += "new Node(";
                    jsonFavoriteList += "\"" + favorite.getFavoriteId() + "\",";
                    jsonFavoriteList += "\"" + favorite.getParentId().trim() + "\",";
                    jsonFavoriteList += "\"" + favorite.getFavoriteName() + "\",";
                    jsonFavoriteList += "\"CNODE\",";
                    jsonFavoriteList += "\"Y\",";
                    jsonFavoriteList += favorite.getDepth() + ",";
                    jsonFavoriteList += favorite.getSortOrder() + ",";
                    jsonFavoriteList += "\"\",";
                    jsonFavoriteList += "1";
                    jsonFavoriteList += ")";
                    if (i < (favoriteList.size()-1))
                    {
                        jsonFavoriteList += ",";
                    }
                }
                jsonFavoriteList += "]";
            }
            else
            {
                jsonFavoriteList += "[]";
            }
        }
        catch (Exception e)
        {
            jsonFavoriteList += "[]";
        }
        return jsonFavoriteList;
    }    
    
    /**
     * 사용자 아이디로 즐겨찾기 카테고리 목록 가져오는 메소드이다.
     * @param accountId
     * @return
     */
    public List selectFavoriteList(String accountId)
    {
   	 	List list = null;
        try
        {
        	Favorite obj = new Favorite();
       	 	obj.setAccountId(accountId);
       	 	obj.setParentId(WebPublic.FAVORITE_ROOT_ID);
       	 
       	 	list = (List)sqlMap.queryForList("Favorite.selectFavoriteList", obj);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
        }
        return list;
    }
    
    /**
     * 사용자 아이디로 지식 즐겨찾기  리스트 개수를 가져오는 메소드이다.
     * @param accountId
     * @param favoriteId
     * @param bRecursive
     * @return
     */
    public int selectFavoriteKmListCount(String domainId, String accountId, String favoriteId, boolean bRecursive)
    {
   	 
   	 	int iResult = 0;    	 
        Favorite obj = new Favorite();
        obj.setDomainId(domainId);
        obj.setAccountId(accountId);
        obj.setServiceType(WebPublic.SERVICE_TYPE_KB);
        obj.setFavoriteId(favoriteId);
        try
        {
        	if (bRecursive)
        		iResult = ((Integer)sqlMap.queryForObject("Favorite.selectFavoriteKmListCountRecursive", obj)).intValue();
        	else
        		iResult = ((Integer)sqlMap.queryForObject("Favorite.selectFavoriteKmListCount", obj)).intValue();
        }
        catch (SQLException e)
        {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return iResult;
    }
    
    /**
     * 사용자 아이디로 지식 즐겨찾기  리스트를 가져오는 메소드이다. (TOP-N개)
     * @param accountId
     * @return
     */
    public List selectFavoriteKmList(int pageNo, int rowsPerPage, String domainId, String accountId, String favoriteId, boolean bRecursive)
    {
   	 
   	 	List list = null;    	 
        Favorite obj = new Favorite();
        obj.setDomainId(domainId);
        obj.setAccountId(accountId);
        obj.setServiceType(WebPublic.SERVICE_TYPE_KB);
        obj.setFavoriteId(favoriteId);
        obj.setStartNo((pageNo-1) * rowsPerPage + 1);
   	 	obj.setEndNo(pageNo * rowsPerPage);
   	 	obj.setRowsPerPage(rowsPerPage);
   	 	
        try
        {
        	if (bRecursive)
        		list = (List) sqlMap.queryForList("Favorite.selectFavoriteKmListRecursive", obj);
        	else
        		list = (List) sqlMap.queryForList("Favorite.selectFavoriteKmList", obj);
        }
        catch (SQLException e)
        {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return list;
    }
    
    /**
     * 즐겨찾기의 지식을 삭제하는 메소드
     * @param favoriteId
     * @param kmId
     * @return
     */
    public boolean deleteFavoriteKm(String favoriteId, String kmId)
    {
        boolean result = false;
        try
        {        	              
            Favorite obj = new Favorite();
            obj.setFavoriteId(favoriteId);
            obj.setKmId(kmId);
            obj.setServiceType(WebPublic.SERVICE_TYPE_KB);
            sqlMap.delete("Favorite.deleteFavoriteKm", obj);             
            
            result = true;
        }
        catch (SQLException e)
        {
            logger.error(e.getMessage());
        }
        return result;
    }
    
    /**
     * 사용자 아이디의 최상위 루트 즐겨찾기 카테고리 아이디를 가져오는 메소드
     * @param accountId
     * @return
     */
    public String selectRootFavoriteId(String accountId)
    {        
        String result = null;
        try
        {
            result = (String)sqlMap.queryForObject("Favorite.selectRootFavoriteId", accountId);            
        }
        catch (Exception e)
        {
        	logger.error(e.getMessage());
        }
        return result;
    }   
    
    /**
     * 즐겨찾기 카테고리의 다음 키를 가져오는 메소드
     * @return
     * @throws SQLException
     */
    public String selectNextFavoriteKey() throws SQLException
    {
        String strFavoriteId = (String)sqlMap.queryForObject("Favorite.selectNextKey");
        return strFavoriteId;
    }
    
    /**
     * 즐겨찾기 카테고리를 추가하는 메소드
     * @param accountId
     * @param parentId
     * @param favoriteName
     * @param depth
     * @return
     */
    public String insertFavorite(String accountId, String parentId, String favoriteName, int depth)
    {
        String favoriteId = "";
        try
        {
            String currDate = DateUtil.getCurrDateTimeStamp();
            favoriteId = selectNextFavoriteKey();
            Favorite favorite = new Favorite();
            favorite.setFavoriteId(favoriteId);
            favorite.setParentId(parentId);
            favorite.setFavoriteName(favoriteName);
            favorite.setAccountId(accountId);
            favorite.setDepth(depth); // 어떤값이든 상관없음.
            favorite.setSortOrder(0); // 어떤값이든 상관없음.
            favorite.setCreatedBy(accountId);
            favorite.setCreatedDate(currDate);
            favorite.setUpdatedBy(accountId);
            favorite.setUpdatedDate(currDate);

            sqlMap.insert("Favorite.insert", favorite);

        }
        catch(Exception e)
        {
            favoriteId = "";
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        return favoriteId;
    }
    
    /**
     * 즐겨찾기 카테고리 이름을 변경하는 메소드
     * @param favoriteId
     * @param favoriteName
     * @param accountId
     * @return
     */
    public boolean updateFavoriteName(String favoriteId, String favoriteName, String accountId)
    {
        boolean success = false;
        String currDate = DateUtil.getCurrDateTimeStamp();

        Favorite favorite = new Favorite();
        favorite.setFavoriteId(favoriteId);
        favorite.setAccountId(accountId);
        favorite.setFavoriteName(favoriteName);
        favorite.setUpdatedBy(accountId);
        favorite.setUpdatedDate(currDate);
        try
        {
            sqlMap.update("Favorite.updateFavoriteName", favorite);
            success = true;
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return success;
    }
    
    /**
     * 즐겨찾기 폴더를 삭제하는 메소드(하위포함)
     * @param favoriteId
     * @return
     */
    public boolean deleteFavoriteRecursive(String favoriteId)
    {
    	boolean success = false;

        try
        {
            sqlMap.delete("Favorite.deleteFavoriteRecursive", favoriteId);
            success = true;
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
        }
        return success;
    }
    
    /**
     * 즐겨찾기 지식을 폴더로 이동하는 메소드
     * @param kmIds
     * @param sourceFavoriteId
     * @param targetFavoriteId
     * @return
     */
	public boolean moveFavoriteKm(String kmIds, String sourceFavoriteId, String targetFavoriteId)
    {
        boolean success = false;
        String currDate = DateUtil.getCurrDateTimeStamp();
        IdListForm kmIdList = new IdListForm();
        kmIdList.setRowIds(kmIds);
        kmIdList.setValue(sourceFavoriteId);
        kmIdList.setTargetId(targetFavoriteId);
        kmIdList.setUpdatedDate(currDate);
        try
        {
            sqlMap.update("Favorite.moveFavoriteKm", kmIdList);
            success = true;
        }
        catch(SQLException e)
        {
            logger.error(e.getMessage());
        }

        return success;
    }
	
	/**
	 * 즐겨찾기 카테고리에 즐겨찾기를 추가하는 메소드이다.
	 * @param favoriteId
	 * @param kmId
	 * @param title
	 * @return
	 */
	public Hashtable addFavoriteKm(String domainId, String accountId, String favoriteId, String kmId, String title)
    {
		Hashtable htResult = new Hashtable();
        try
        {
        	String currDate = DateUtil.getCurrDateTimeStamp();
        	
        	Favorite obj = new Favorite();
        	obj.setDomainId(domainId);
       	 	obj.setFavoriteId(favoriteId);
       	 	obj.setAccountId(accountId);
       	 	obj.setKmId(kmId);
       	 	obj.setServiceType(WebPublic.SERVICE_TYPE_KB);
       	 	obj.setRelationName(title);
       	 	obj.setCreatedDate(currDate);
       	 	
       	 	int iResult = ((Integer)sqlMap.queryForObject("Favorite.selectFavoriteKmListCountByKmId", obj)).intValue();
       	 	if (iResult > 0) // 이미 해당 카테고리에 즐겨찾기가 추가되어있음
       	 	{
       	 		htResult.put(WebPublic.RESULT_STRING, WebPublic.FAIL_STRING);
       	 		htResult.put(WebPublic.MESSAGE_STRING, "DUPLICATE");
       	 		return htResult;
       	 	}
            sqlMap.insert("Favorite.insertFavoriteKm", obj);
            htResult.put(WebPublic.RESULT_STRING, WebPublic.SUCCESS_STRING);
            htResult.put("favoriteId", favoriteId);
        }
        catch(Exception e)
        {
            favoriteId = "";
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        return htResult;
    }
    
}